package com.zqc.controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.zqc.common.lang.Const;
import com.zqc.common.lang.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
public class AuthController extends BaseController {

    @Autowired
    public Producer producer;

    @GetMapping("/captcha")
    public Result captcha() throws IOException {
        // 创建key
        String key = UUID.randomUUID().toString();
        // 创建验证码
        String code = producer.createText();

        // 使用验证码生成图片
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 将生成的图片写出
        ImageIO.write(image, "jpeg", outputStream);

        // BASE64编码
        Base64Encoder encoder = new Base64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());
        // 将生成的验证码和key存到redis中存到
        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);

        // 将验证码和token返回
        return Result.succ(
                MapUtil.builder()
                        .put("token", key)
                        .put("captchaImg", base64Img)
                        .build()
        );
    }
}
